package com.xuecheng.media.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.MediaConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.MediaDto;
import com.xuecheng.commons.model.dto.MediaQueryDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.dto.VodUploadDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.media.config.VodTemplate;
import com.xuecheng.media.domain.Media;
import com.xuecheng.media.mapper.MediaMapper;
import com.xuecheng.media.service.MediaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-12-07
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {
    @Autowired
    private VodTemplate vodTemplate;
    // 获取上传凭证
    @Override
    public ResponseResult<VodUploadVo> vodToken(VodUploadDto dto) {
        // 1.参数校验
        if (StrUtil.isEmpty(dto.getFileName()) || StrUtil.isEmpty(dto.getTitle())) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        try {
            //获取上传凭证
            CreateUploadVideoResponse response = vodTemplate.createUploadVideo(dto.getTitle(), dto.getFileName());
            //转vo
            VodUploadVo vodUploadVo = BeanHelper.copyProperties(response, VodUploadVo.class);
            //返回vo结果
            return ResponseResult.okResult(vodUploadVo);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.ALIYUNERROR);
        }

    }
    // 刷新上传凭证
    @Override
    public ResponseResult<VodUploadVo> refreshVodToken(String videoId) {
        // 1.参数校验
        if (StrUtil.isEmpty(videoId)) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        try {
            // 2.刷新token
            RefreshUploadVideoResponse response = vodTemplate.refreshUploadVideo(videoId);
            // 3.转vo
            VodUploadVo vo = BeanHelper.copyProperties(response, VodUploadVo.class);
            // 4.返回vo
            return ResponseResult.okResult(vo);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.ALIYUNERROR);
        }

    }
    // 保存媒资
    @Override
    public ResponseResult saveMedia(MediaDto dto) {
        // 1.校验参数是否为空
        if (StrUtil.isEmpty(dto.getFilename()) ||
         StrUtil.isEmpty(dto.getFileId())||StrUtil.isEmpty(dto.getType())
        ||StrUtil.isEmpty(dto.getBucket())) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        // 2.dto转实体
        Media media = BeanHelper.copyProperties(dto, Media.class);
        //=============================补全信息
        // 3.根据视频id获取播放地址和时长
        GetPlayInfoResponse response = null;
        try {
            response = vodTemplate.getPlayInfo(media.getFileId());
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.ADDEERROR);
        }
        // 3-1 获取上传视频时长   91.1
        String duration = response.getPlayInfoList().get(0).getDuration();
        // 3-2 获取上传视频播放地址
        String playURL = response.getPlayInfoList().get(0).getPlayURL();
        media.setUrl(playURL); // 文件播放地址
        // 视频时长   将91.1秒 ->   01:31分
        Float f = Float.parseFloat(duration);
        LocalTime localTime = LocalTime.MIN.plusMinutes(f.longValue());
        media.setTimelength(localTime.toString());
        media.setUsername(AuthInfoHolder.getUserId().toString()); // 上传人
        media.setCreateDate(new Date()); // 上传时间
        media.setAuditStatus(MediaConstants.AUDIT_UNPAST_STATUS); // 审核状态
        // 5.保存数据库
        this.save(media);
        return ResponseResult.okResult();
    }
    // 媒资预览
    @Override
    public ResponseResult<String> preview(Long mediaId) throws Exception {
        // 1.查询媒资对象
        Media media = this.getById(mediaId);
        // 2.根据视频id查询最新播放地址
        GetPlayInfoResponse playInfo = vodTemplate.getPlayInfo(media.getFileId());
        String playURL = playInfo.getPlayInfoList().get(0).getPlayURL();
        // 3.返回播放地址
        return ResponseResult.okResult(playURL);
    }
    //媒资删除
    @Override
    public ResponseResult deleteMedia(Long mediaId) throws Exception {
        // 1.查询媒资对象
        Media media = this.getById(mediaId);
        // 2.判断审核状态 是否为审核通过
        if (media.getAuditStatus().equals(MediaConstants.AUDIT_PASTED_STATUS)) {
            // 审核通过不让删
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        //删除阿里云
        String fileId = media.getFileId();
        vodTemplate.deleteVideo(fileId);
        //删除数据库
        this.removeById(mediaId);
        //返回ok
        return ResponseResult.okResult();

    }
    // 媒资分页查询
    @Override
    public ResponseResult<MediaVo> findByPage(PageRequest pageRequest, MediaQueryDto dto) {
        //创建分页对象
        Page<Media> mediaPage = new Page<>(pageRequest.getPageNo(),pageRequest.getPageSize());
/*        ArrayList<Media> mediaList = new ArrayList<Media>();
        //条件查询 判断条件不为空进行模糊查询
        if (StrUtil.isNotEmpty(dto.getFilename())){
        LambdaQueryWrapper<Media> lq = new LambdaQueryWrapper<>();
        lq.like(Media::getFilename,dto.getFilename());
            List<Media> list = mediaService.list(lq);
            for (Media media : list) {
                mediaList.add(media);
            }
        }
        if (StrUtil.isNotEmpty(dto.getType())){
            List<Media> list = this.lambdaQuery().eq(Media::getType, dto.getType()).list();
            for (Media media : list) {
                mediaList.add(media);
            }
        }
        if (StrUtil.isNotEmpty(dto.getAuditStatus())){
            List<Media> list = this.lambdaQuery().eq(Media::getAuditStatus, dto.getAuditStatus()).list();
            for (Media media : list) {
                mediaList.add(media);
            }
        }
        Page<Media> page = mediaPage.setRecords(mediaList);*/
        // 2.条件分页查询
        mediaPage = this.lambdaQuery()
                .like(StrUtil.isNotEmpty(dto.getFilename()), Media::getFilename, dto.getFilename())
                .eq(StrUtil.isNotEmpty(dto.getType()), Media::getType, dto.getType())
                .eq(StrUtil.isNotEmpty(dto.getAuditStatus()), Media::getAuditStatus, dto.getAuditStatus())
                .page(mediaPage);
        //将查询出来的集合放出分页对象
        // 3.media转vo
/*        List<Media> list = mediaService.list();
        mediaPage.setRecords(list);*/
        List<Media> mediaList1 = mediaPage.getRecords();
        List<MediaVo> voList = BeanHelper.copyWithCollection(mediaList1, MediaVo.class);
        // 4.返回分页
        return PageResponseResult.okResult(mediaPage.getTotal(),voList);
    }

    @Override
    public ResponseResult<ResourceVo> mediaUrl(Long mediaId) throws Exception {
        // 1.查询媒资对象
        Media media = this.getById(mediaId);
        // 2.根据视频id查询最新播放地址
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(media.getFileId());
        String playURL = response.getPlayInfoList().get(0).getPlayURL();
        // 3.封装vo
        ResourceVo vo = new ResourceVo();
        vo.setPlayUrl(playURL);
        // 4.返回vo
        return ResponseResult.okResult(vo);

    }
}
